//
//  SEGChangePhoneNumberViewController.m
//  ExcellentHome
//
//  Created by 梁昆 on 2017/10/17.
//  Copyright © 2017年 陈区. All rights reserved.
//

#import "SEGChangePhoneNumberViewController.h"
#import "SEGChangeNewNumberViewController.h"
#import <Commom/UITextField+Limit.h>
#import <Commom/SEGSafaKeyboard.h>

#import "SEGChangePhoneNumberViewModel.h"

@interface SEGChangePhoneNumberViewController ()<UITextFieldDelegate, SGETextFieldLimitDelegate>

/// 背景视图
@property (nonatomic, strong) UIView *bgView;
/// 已绑定的手机号
@property (nonatomic, strong) UILabel *bindNum;
/// 分割线
@property (nonatomic, strong) UIView *line;
/// 分割线
@property (nonatomic, strong) UIView *line2;
/// 输入验证码
@property (nonatomic, strong) UITextField *inputCode;
/// 获取验证码
@property (nonatomic, strong) UIButton *getMessButton;
/// 图片验证码
@property (nonatomic, strong) UITextField *checkImgText;
/// 获取验证视图
@property (nonatomic, strong) UIImageView *checkImgView;
/// 重新获取验证码按钮
@property (nonatomic, strong) UIButton *freshCheckImgBtn;
/// 手机号停用，联系物业提示
@property (nonatomic, strong) UILabel *hintMessage;
/// 下一步按钮
@property (nonatomic, strong) UIButton *nextButton;

/// 定时器取消
@property (nonatomic, strong) RACDisposable *disposable;
/// viewModel
@property (nonatomic, strong) SEGChangePhoneNumberViewModel *viewModel;

@end

@implementation SEGChangePhoneNumberViewController

- (void)dealloc {
    [self.disposable dispose];
}
- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = @"修改手机号";
    self.view.backgroundColor = kColor_bg;
    [self setupUI];
    
    // 刷新图片验证码
    [self freshCheckImgBtnClick];
    // 绑定信号
    [self seg_bindSingal];
}

#pragma mark - Bind
- (void)seg_bindSingal {
    RACChannelTo(self.viewModel, checkImgStr) = self.checkImgText.rac_newTextChannel;
    RAC(self.viewModel, smsCodeStr) = self.inputCode.rac_textSignal;
}

#pragma mark - UI
- (void)setupUI {
    //背景视图
    [self.view addSubview:self.bgView];
    [self.bgView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.equalTo(self.view);
        make.height.mas_equalTo(134);
    }];
    
    // 已绑定的手机号
    [self.view addSubview:self.bindNum];
    [self.bindNum mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self.bgView).mas_offset(15);
        make.top.equalTo(self.bgView);
        make.height.mas_equalTo(45);
    }];
    
    [self.view addSubview:self.line];
    [self.line mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.bgView).mas_offset(44);
        make.left.right.equalTo(self.bgView);
        make.height.mas_equalTo(1);
    }];
    
    [self.view addSubview:self.line2];
    [self.line2 mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.line.mas_bottom).mas_offset(44);
        make.left.right.equalTo(self.bgView);
        make.height.mas_equalTo(1);
    }];
    
    // 图片验证码输入框
    [self.view addSubview:self.checkImgText];
    [self.view addSubview:self.checkImgView];
    [self.checkImgText mas_makeConstraints:^(MASConstraintMaker* make) {
        make.top.equalTo(self.line.mas_bottom);
        make.left.equalTo(self.bgView).mas_offset(15);
        make.right.equalTo(self.checkImgView.mas_left).mas_offset(-10);
        make.height.mas_equalTo(45);
    }];
    
    [self.freshCheckImgBtn sizeToFit];
    
    // 验证码图片
    [self.view addSubview:self.freshCheckImgBtn];
    [self.checkImgView mas_makeConstraints:^(MASConstraintMaker* make) {
        make.centerY.equalTo(self.checkImgText);
        make.right.equalTo(self.freshCheckImgBtn.mas_left).mas_offset(-15);
        make.width.mas_equalTo(72);
        make.height.mas_equalTo(30);
    }];
    
    // 验证码刷新按钮
    [self.freshCheckImgBtn mas_makeConstraints:^(MASConstraintMaker* make) {
        make.right.equalTo(self.bgView).mas_offset(-15);
        make.centerY.equalTo(self.checkImgView);
    }];
    
    //输入验证码
    [self.view addSubview:self.inputCode];
    [self.inputCode mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.line2.mas_bottom);
        make.left.equalTo(self.bgView).mas_offset(15);
        make.height.mas_equalTo(45);
    }];
    
    // 获取验证码
    [self.view addSubview:self.getMessButton];
    [self.getMessButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.equalTo(self.inputCode);
        make.right.equalTo(self.bgView).mas_offset(-15);
    }];
    
    // 手机号停用，联系物业提示
    [self.view addSubview:self.hintMessage];
    [self.hintMessage mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.bgView.mas_bottom).mas_offset(10);
        make.right.equalTo(self.bgView).mas_offset(-15);
    }];
    
    //下一步按钮
    [self.view addSubview:self.nextButton];
    [self.nextButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.bgView.mas_bottom).mas_offset(50);
        make.left.equalTo(self.view).mas_offset(15);
        make.right.equalTo(self.view).mas_offset(-15);
        make.height.mas_equalTo(44);
    }];
}

#pragma mark - Event
// 获取验证码的点击方法
- (void)getMessButtonClick {
    @weakify(self);
    [self.viewModel.captchasSignal subscribeNext:^(id  _Nullable x) {
        @strongify(self);
        [SEGAlertView showTmepMessageWithMessage:@"验证码已发送"];
        [self sentPhoneCodeTimeMethod];
    } error:^(NSError * _Nullable error) {
        @strongify(self);
        [SEGAlertView showTmepMessageWithMessage:error.localizedFailureReason];
        if (error.code == 1) {
            // 刷新图形验证码
            [self freshCheckImgBtnClick];
        }
    }];
}
// 计时器发送验证码
- (void)sentPhoneCodeTimeMethod {
    // 倒计时时间 —— 60秒
    __block NSInteger timeOut = 59;
    @weakify(self);
    self.disposable = [[RACSignal interval:1 onScheduler:[RACScheduler mainThreadScheduler]] subscribeNext:^(NSDate * _Nullable x) {
        @strongify(self);
        if (timeOut < 0) {
            [self.disposable dispose];
            [self.getMessButton setTitle:kRefreshGetMessageCodeTitle forState:UIControlStateNormal];
            self.getMessButton.enabled = YES;
        } else {
            [UIView beginAnimations:nil context:nil];
            [UIView setAnimationDuration:1.0];
            [self.getMessButton setTitle:[NSString stringWithFormat:@"%ldS", timeOut] forState:UIControlStateNormal];
            self.getMessButton.contentHorizontalAlignment = UIControlContentHorizontalAlignmentRight;
            [UIView commitAnimations];
            //计时器件不允许点击
            self.getMessButton.enabled = NO;
            timeOut --;
        }
    }];
}
// 刷新图片验证码
- (void)freshCheckImgBtnClick {
    @weakify(self);
    [self.viewModel.refreshImgSignal subscribeNext:^(UIImage *decodedImage) {
        @strongify(self);
        if (decodedImage) {
            [self.checkImgView setImage:decodedImage];
        } else {
            [self.checkImgView setImage:[UIImage imageWithContentsOfFile:SEGPicName(@"pic_default_72_72")]];
        }
    } error:^(NSError * _Nullable error) {
        [SEGAlertView showTmepMessageWithMessage:error.localizedFailureReason];
    }];
}
// 下一步按钮点击的网络请求
- (void)nextButtonClick {
    @weakify(self);
    [self.viewModel.nextSignal subscribeNext:^(id  _Nullable x) {
        @strongify(self);
        // 跳转到更换手机号页面
        SEGChangeNewNumberViewController *changeNewNumberVC = [[SEGChangeNewNumberViewController alloc] init];
        [self.navigationController pushViewController:changeNewNumberVC animated:YES];
    } error:^(NSError * _Nullable error) {
        [SEGAlertView showTmepMessageWithMessage:error.localizedFailureReason];
    }];
}
- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
    [self.view endEditing:YES];
}

#pragma mark - SGETextFieldLimitDelegate
- (void)limitTextFileDidChange:(UITextField *)textField {
    if (self.checkImgText.text.length > 0 && self.inputCode.text.length > 0) {
        self.nextButton.enabled = YES;
    } else {
        self.nextButton.enabled = NO;
    }
}
#pragma mark - UITextFieldDelegate
- (BOOL)textFieldShouldReturn:(UITextField *)textField {
    [textField resignFirstResponder];
    return YES;
}

#pragma mark - Getter
- (UIView *)bgView {
    if (!_bgView) {
        _bgView = [[UIView alloc] init];
        _bgView.backgroundColor = kColor_W;
    }
    return _bgView;
}
// 已绑定的手机号
- (UILabel *)bindNum {
    if (!_bindNum) {
        _bindNum = [[UILabel alloc] init];
        NSString *tel = [SEGProfileManager sharedManager].profile.tel;
        NSString *numberString = [tel stringByReplacingCharactersInRange:NSMakeRange(3, 4) withString:@"****"];
        _bindNum.text = [NSString stringWithFormat:@"已绑定%@手机号",numberString];
        _bindNum.textColor = kColor_2;
        _bindNum.font = kFont_15;
    }
    return _bindNum;
}
- (UIView *)line {
    if (!_line) {
        _line = [[UIView alloc] init];
        _line.backgroundColor = kColor_L2;
    }
    return _line;
}
- (UIView *)line2 {
    if (!_line2) {
        _line2 = [[UIView alloc] init];
        _line2.backgroundColor = kColor_L2;
    }
    return _line2;
}
// 输入验证码textfield
- (UITextField *)inputCode {
    if (!_inputCode) {
        _inputCode = [[UITextField alloc] init];
        [_inputCode setTextColor:kColor_1];
        [_inputCode setTintColor:kColor_T];
        [_inputCode setFont:kFont_16];
        [_inputCode setAttributedPlaceholder:[[NSAttributedString alloc] initWithString:@"请输入已绑定手机号验证码" attributes:@{NSForegroundColorAttributeName:kColor_C}]];
        _inputCode.clearsOnBeginEditing = NO;
        _inputCode.keyboardType = UIKeyboardTypeNumbersAndPunctuation;
        _inputCode.returnKeyType = UIReturnKeyDone;
        _inputCode.delegate = self;
        [_inputCode configSMSCodeInputLimitWithDelegate:self];
    }
    return _inputCode;
}
// 获取验证码按钮
- (UIButton *)getMessButton {
    if (!_getMessButton) {
        // 发送验证码 按钮
        _getMessButton = [[UIButton alloc] init];
        [_getMessButton setTitle:kGetMessageCodeTitle forState:UIControlStateNormal];
        _getMessButton.contentHorizontalAlignment = UIControlContentHorizontalAlignmentRight;
        [UIView commitAnimations];
        _getMessButton.titleLabel.font = [UIFont systemFontOfSize:16];
        [_getMessButton setTitleColor:kColor_T forState:UIControlStateNormal];
        [_getMessButton setTitleColor:kColor_3 forState:UIControlStateDisabled];
        // 发送事件
        [_getMessButton addTarget:self action:@selector(getMessButtonClick) forControlEvents:UIControlEventTouchUpInside];
    }
    return _getMessButton;
}
// 图片验证码
- (UITextField *)checkImgText {
    if (!_checkImgText) {
        _checkImgText = [[UITextField alloc] init];
        [_checkImgText setTextColor:kColor_1];
        [_checkImgText setFont:[UIFont systemFontOfSize:16]];
        [_checkImgText setAttributedPlaceholder:[[NSAttributedString alloc] initWithString:@"图片验证码" attributes:@{NSForegroundColorAttributeName:kColor_C}]];
        _checkImgText.clearsOnBeginEditing = NO;
        _checkImgText.delegate = self;
        _checkImgText.clearsOnBeginEditing = NO;
        [_checkImgText setTintColor:kColor_T];
        _checkImgText.clearButtonMode = UITextFieldViewModeNever;
        _checkImgText.returnKeyType = UIReturnKeyDone;
        [_checkImgText configImgCodeInputLimitWithDelegate:self];
        _checkImgText.autocorrectionType = UITextAutocorrectionTypeNo;
    }
    return _checkImgText;
}
// 验证码图片
- (UIImageView *)checkImgView {
    if (!_checkImgView) {
        _checkImgView = [[UIImageView alloc] initWithImage:[UIImage imageWithContentsOfFile:SEGPicName(@"pic_default_72_72")]];
        [_checkImgView setUserInteractionEnabled:YES];
        
        UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(freshCheckImgBtnClick)];
        [_checkImgView addGestureRecognizer:tap];
    }
    return _checkImgView;
}
// 刷新图片验证码
- (UIButton *)freshCheckImgBtn {
    if (!_freshCheckImgBtn) {
        // 发送语音验证码 按钮
        _freshCheckImgBtn = [[UIButton alloc] init];
        [_freshCheckImgBtn setTitle:@"换一张" forState:UIControlStateNormal];
        [_freshCheckImgBtn.titleLabel setFont:[UIFont systemFontOfSize:16]];
        [_freshCheckImgBtn setTitleColor:kColor_T forState:UIControlStateNormal];
        _freshCheckImgBtn.contentVerticalAlignment = UIControlContentVerticalAlignmentCenter;
        // 发送事件
        [_freshCheckImgBtn addTarget:self action:@selector(freshCheckImgBtnClick) forControlEvents:UIControlEventTouchUpInside];
    }
    return _freshCheckImgBtn;
}
// 手机号停用，联系物业提示
- (UILabel *)hintMessage {
    if (!_hintMessage) {
        _hintMessage = [[UILabel alloc] init];
        _hintMessage.text = @"如绑定手机号已停用，请联系物业";
        [_hintMessage setTextColor:kColor_3];
        [_hintMessage setFont:[UIFont systemFontOfSize:13]];
    }
    return _hintMessage;
}
// 下一步按钮
- (UIButton *)nextButton {
    if (!_nextButton) {
        _nextButton = [[UIButton alloc] init];
        [_nextButton setTitle:@"下一步" forState:UIControlStateNormal];
        _nextButton.titleLabel.font = [UIFont systemFontOfSize:16];
        [_nextButton setTitleColor:kColor_W forState:UIControlStateNormal];
        _nextButton.backgroundColor = kColor_T;
        [_nextButton setBackgroundImage:[UIImage imageWithColor:kColor_T] forState:UIControlStateNormal];
        [_nextButton setBackgroundImage:[UIImage imageWithColor:kColor_T_Press] forState:UIControlStateHighlighted];
        [_nextButton setBackgroundImage:[UIImage imageWithColor:kColor_L2] forState:UIControlStateDisabled];
        _nextButton.layer.cornerRadius = 2;
        _nextButton.layer.masksToBounds = YES;
        [_nextButton addTarget:self action:@selector(nextButtonClick) forControlEvents:UIControlEventTouchUpInside];
        _nextButton.enabled = NO;
    }
    return _nextButton;
}
- (SEGChangePhoneNumberViewModel *)viewModel {
    if (!_viewModel) _viewModel = [SEGChangePhoneNumberViewModel new];
    return _viewModel;
}

@end
